package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
/**
 * 订单计时器
 */
public class OrdersTask {
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 自动取消超时订单
     */
    @Scheduled(cron = "* 0/15 * * * ?")
    public void ProcessTimeoutOrders() {
        //符合订单的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //获取符合条件的订单数据  根据状态和时间查询
        List<Orders> orders = orderMapper.selectOrderByStatusAndTime(Orders.PENDING_PAYMENT, time);
        //判断订单是否有数据
        if (orders != null && orders.size() > 0) {
            //遍历订单
            orders.forEach(order->{
                //修改订单状态
                order.setStatus(Orders.CANCELLED);
                //取消原因
                order.setCancelReason("订单超时，订单已取消");
                //取消时间
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 自动完成配送中订单
     */
    @Scheduled(cron = "* * 13 * * ?")
    public void ProcessDeliveryOrders() {
        //符合订单的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-6);
        //获取符合条件的订单数据  根据状态和时间查询
        List<Orders> orders = orderMapper.selectOrderByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, time);
        //判断订单是否有数据
        if (orders != null && orders.size() > 0) {
            //遍历订单
            orders.forEach(order->{
                //修改订单状态
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
